package com.itheima.interceptor;

import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception  {
        {

//1.
            System.out.println("TokenInterceptor使用的线程名称是：" + Thread.currentThread().getName());
//            String url =request.getRequestURL().toString();
//            if(url.contains("login")){
//                log.info("登录请求 , 直接放行");
//                return true;
//            }

            String token = request.getHeader("token");
            try {
                Claims claims = JwtUtils.parseJWT(token);
                Integer userId = claims.get("userId", Integer.class);
                CurrentHolder.setUserId(userId);
            }catch (Exception e){
                e.printStackTrace();
                log.info("解析令牌失败, 返回错误结果");
                response.setStatus(401);
                return false;
            }
            log.info("令牌合法, 放行");
           return true;
        }
    }

    //目标资源方法执行后执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle ... ");
    }

    //视图渲染完毕后执行，最后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion .... ");
    }
}
